package org.t235.user.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.t235.commons.model.AjaxResult;
import org.t235.commons.model.Order;
import org.t235.commons.model.User;
import org.t235.feign.order.OrderServiceRemote;
import org.t235.user.service.UserService;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RefreshScope
public class UserController {
//    @Value("${blackIpList}")
    private String blackIpList;
    @Value("${user.id}")
    private String userId;
    @Value("${user.name}")
    private String userName;
    @Value("${user.age}")
    private String userAge;

    @Resource
    private UserService userService;
    @Value("${server.port}")
    private String port;
    @Resource
    private OrderServiceRemote orderServiceRemote;

    @SentinelResource(value = "userinfo", blockHandler = "blockUserinfo")
    @GetMapping("/userinfo")
    public AjaxResult userinfo() {
        return AjaxResult.success(userId + "," + userName + "," + userAge);
    }

    public AjaxResult blockUserinfo(BlockException ex) {
        return AjaxResult.error("user-service.userinfo接口被限流了" + ex.getMessage());
    }

    @GetMapping("/blackIpList")
    public AjaxResult blackIpList() {
        return AjaxResult.success(blackIpList);
    }

    @GetMapping("/findById/{userId}")
    public AjaxResult findById(@PathVariable("userId") Long userId) {
        List<User> users = userService.findAll().stream().filter(user -> user.getId().equals(userId)).collect(Collectors.toList());
        if(users.isEmpty()) {
            return AjaxResult.error("not found:" + userId);
        } else {
            User user = users.get(0);
            AjaxResult orderResult = orderServiceRemote.findByUserId(userId);
            if(orderResult.getCode() != AjaxResult.SUCCESS) {
                return AjaxResult.success(orderResult.getMsg(), user);
            } else {
                user.setOrders((List<Order>) orderResult.getData());
                return AjaxResult.success(user);
            }
        }
    }
    @GetMapping
    public AjaxResult findAll() {
        List<User> list = userService.findAll().stream().map(user -> {
            user.setName(user.getName() + port);
            return user;
        }).collect(Collectors.toList());
       /* List<User> all = userService.findAll();
        for (User user : all) {
            user.setName(user.getName() + port);
        }*/
        return AjaxResult.success(list);
    }
}
